var UserComm = {
    Url: CTX + '/sys/user',
    DeptUrl: CTX + '/sys/dept'
};
var UserMVC = {
    Req: {
        list: {method: 'GET', url: UserComm.Url},
        add: {method: 'POST', url: UserComm.Url},
        update: {method: 'PUT', url: UserComm.Url},
        del: {method: 'DELETE', url: UserComm.Url},
        export: {method: 'POST', url: UserComm.Url + '/export'},
        resetPassword: {method: 'POST', url: UserComm.Url + '/resetPassword'},
        findRoleAndAcl: {method: 'GET', url: UserComm.Url + '/findRoleAndAcl'},
        findDeptTree: {method: 'GET', url: UserComm.DeptUrl}
    },
    DOMs: null,
    data: {
        deptMap: {},
        statusMap: {},
        statusList: {}
    },
    Columns: {
        user: [[{
            field: '_opts_',
            title: '操作',
            width: 120,
            align: 'center',
            formatter: function (v, row, i) {
                var ary = [];
                ary.push('<a href="javascript:;" permission="sys:user:update" class="row-btn" title="修改" onclick="updateUser(' + i + ')"><i class=" fa fa-edit"></i></a>');
                ary.push('<a href="javascript:;" permission="sys:user:del" class="row-btn" title="删除" onclick="deleteUsers(' + i + ')"><i class="fa fa-trash"></i></a>');
                ary.push('<a href="javascript:;" permission="sys:user:resetPwd" class="row-btn" title="密码重置" onclick="resetPassword(' + i + ')"><i class="fa fa-key"></i></a>');
                ary.push('<a href="javascript:;" class="row-btn" title="关联信息" onclick="relatedRoleAndAcl(' + i + ')"><i class="fa fa-info-circle"></i></a>');
                return ary.join('&nbsp;<span class="btn-separator"></span>&nbsp;');
            }
        }, {
            field: 'id',
            title: '用户ID',
            width: 80,
            sortable: true
        }, {
            field: 'username',
            title: '用户名',
            width: 120,
            sortable: true,
            formatter: function (v, row, i) {
                return '<a href="javascript:;" class="row-btn" title="' + row.username + '" onclick="seeUser(' + i + ')">' + v + '</a>';
            }
        }, {
            field: 'nickName',
            title: '昵称',
            width: 120
        }, {
            field: 'email',
            title: '邮箱',
            width: 160
        }, {
            field: 'deptId',
            title: '部门',
            width: 150,
            formatter: function (v, row, i) {
                v = v ? v : '';
                var dept = v ? UserMVC.data.deptMap[v] : '';
                return '<span title="' + v + '">' + (dept ? dept.name : v) + '</span>';
            }
        }, {
            field: 'status',
            title: '状态',
            width: 80,
            formatter: function (v, row, i) {
                var text = UserMVC.data.statusMap[v];
                if (text) {
                    var color = v == '1' ? 'green' : 'red';
                    return $.app.formatString('<span style="color: {0};"><i class="{2}"></i> {1}</span>', color, text, '');
                }
                return v;
            }
        }, {
            field: 'note',
            title: '备注',
            width: 150,
            formatter: function (v, row, i) {
                v = v ? v : '';
                return $.app.formatString('<span title="{0}">{0}</span>', v);
            }
        }]]
    }
};

$(function () {
    UserMVC.DOMs = {
        $searchForm: $('#searchForm'),
        $searchBtn: $('#searchBtn'),
        $resetBtn: $('#resetBtn'),
        $dataGrid: $('#userGrid'),
        $dlg: $('#dlg')
    };


    $.when(ajaxDept(), ajaxStatus())
        .done(function (a1, a2) {
            console.info(a1, a2);
            initPage(UserMVC.DOMs, UserMVC.Req, {
                singleSelect: true,
                sortName: 'id',
                sortOrder: 'asc',
                columns: UserMVC.Columns.user,
                onSelect: function (index, row) {
                    relatedRoleAndAcl(index);
                },
                onLoadSuccess: function (data) {
                    if (data && data.rows && data.rows.length > 0) {
                        $.app.controlPermission();
                        $(this).datagrid('selectRow', 0);
                    }
                }
            }, getQueryParams, true);
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            $.app.info(jqXHR, textStatus, errorThrown);
        });
});


// 数据查询方法，作用于查询、导出
function getQueryParams() {
    return UserMVC.DOMs.$searchForm.serializeForm();
}

// 添加
function addUser(deptId) {
    var $dlg = UserMVC.DOMs.$dlg, $grid = UserMVC.DOMs.$dataGrid;
    var $form = $dlg.find('form');
    $form.form('reset');
    if (deptId) {
        $('#fm_deptId').combotree('setValue', deptId);
    }
    $dlg.dialog({
        title: '新增用户',
        modal: true,
        inline: true,
        buttons: [{
            text: '确定',
            iconCls: 'e-icon fa fa-save',
            plain: true,
            handler: function () {
                var formObj = $form.serializeForm();
                $form.submitEForm(UserMVC.Req.add, formObj, function (userId) {
                    $grid.datagrid('reload', {
                        id: userId
                    });
                    $dlg.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

// 修改
function updateUser(rowIndex) {
    var $dlg = UserMVC.DOMs.$dlg, $grid = UserMVC.DOMs.$dataGrid;
    var user = null;
    if (rowIndex || rowIndex === 0) {// 第0行也可以修改
        $grid.datagrid('unselectAll');
        user = $grid.datagrid("getRows")[rowIndex];
    } else {
        user = $grid.datagrid('getSelections')[0];
    }
    if (!user) {
        $.showMsg('请选择一行数据！');
        return;
    }

    var $form = $dlg.find('form');
    $form.form('load', user);
    $dlg.dialog({
        title: '修改用户',
        modal: true,
        buttons: [{
            text: '确定',
            iconCls: 'fa fa-save',
            plain: true,
            handler: function () {
                var formObj = $form.serializeForm();
                $form.submitEForm(UserMVC.Req.update, formObj, function (userId) {
                    $grid.datagrid('reload', {
                        id: userId
                    });
                    $dlg.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

// 查看
function seeUser(rowIndex) {
    var $dlg = UserMVC.DOMs.$dlg, $grid = UserMVC.DOMs.$dataGrid;
    $grid.datagrid('unselectAll');
    var user = $grid.datagrid("getRows")[rowIndex];

    $dlg.find('form').form('load', user);
    $dlg.dialog({
        title: '查看用户',
        modal: true,
        buttons: [{
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

// 删除，包括行内删除和批量删除
function deleteUsers(rowIndex) {
    var $grid = UserMVC.DOMs.$dataGrid;
    if (rowIndex || rowIndex === 0) {// 第0行也可以删除
        $grid.datagrid('unselectAll');
        var row = $grid.datagrid("getRows")[rowIndex];
        // $.messager.confirm('确认', '确定要删除用户[' + row.username + ']吗？', function (r) {
        //     if (r) {
        //         doDelete([row.id]);
        //     }
        // });
        $.confirmMsg('确定要删除用户[' + row.username + ']吗？', function () {
            doDelete([row.id], $grid);
        });
    } else {
        var rows = $grid.datagrid('getSelections'), ids = [];
        if (rows && rows.length) {
            $.each(rows, function (i, row) {
                ids.push(row.id);
            });
            $.confirmMsg('确定要删除选择的[' + ids.length + ']条记录？', function () {
                doDelete(ids, $grid);
            });
        } else {
            $.showMsg('请选择要删除的记录');
        }
    }
}

// 请求后台删除
function doDelete(ids, $reloadGrid) {
    $.ajax({
        type: UserMVC.Req.del.method,
        url: UserMVC.Req.del.url,
        data: {
            ids: ids.join(',')
        },
        dataType: 'json',
        success: function (result) {
            $.dealResultData(result);
            $reloadGrid.datagrid('reload');
        }
    });
}

/**
 * 重置密码
 */
function resetPassword(rowIndex) {
    var $grid = UserMVC.DOMs.$dataGrid;
    if (rowIndex || rowIndex === 0) {
        $grid.datagrid('unselectAll');
        var row = $grid.datagrid("getRows")[rowIndex];
        $.confirmMsg('确定要重置用户[' + row.username + ']的密码吗？', function () {
            doResetPassword([row.id]);
        });
    } else {
        var rows = $grid.datagrid('getSelections'), ids = [];
        if (rows.length > 0) {
            $.each(rows, function (i, row) {
                ids.push(row.id);
            });
            $.confirmMsg('确定要重置选择的[' + ids.length + ']条记录的密码吗？', function () {
                doResetPassword(ids);
            });
        } else {
            $.showMsg('请选择要操作的记录');
        }
    }
}

// 请求后台重置密码
function doResetPassword(ids) {
    $.ajax({
        method: UserMVC.Req.resetPassword.method,
        url: UserMVC.Req.resetPassword.url,
        data: {
            ids: ids.join(',')
        },
        dataType: 'json',
        success: function (result) {
            $.dealResultData(result);
        }
    });
}

function relatedRoleAndAcl(rowIndex) {
    var $grid = UserMVC.DOMs.$dataGrid;
    var user = $grid.datagrid("getRows")[rowIndex];
    var n = $('#userRelatedLayout').layout('panel', 'north');
    var c = $('#userRelatedLayout').layout('panel', 'center');
    n.panel('setTitle', '[' + user.username + ']关联角色');
    c.panel('setTitle', '[' + user.username + ']关联权限');
    $.ajax({
        type: UserMVC.Req.findRoleAndAcl.method,
        url: UserMVC.Req.findRoleAndAcl.url,
        data: {
            userId: user.id
        },
        dataType: 'json',
        success: function (data) {
            if (data && data.status) {
                if (data.status == '200') {
                    var roleData = data.data.roleList;
                    $('#userRoleGrid').datagrid('loadData', roleData);
                    var aclTreeData = data.data.aclTree;
                    aclTreeData = changeTreeGrid2TreeData(aclTreeData, 'id', 'name', 'children');
                    $('#userAclTree').tree('loadData', aclTreeData);
                } else {
                    $.errorMsg(data.msg);
                }
            }
        }
    });
}

function ajaxStatus() {
    return ajaxEnum('com.uvnos4j.matilda.system.enums.UserStatus', function (dict) {
        UserMVC.data.statusMap = dict._map;
        UserMVC.data.statusList = dict._list;

        $('#sf_status').combobox({
            data: UserMVC.data.statusList,
            loadFilter: e_combobox_addall_filter
        });
        $('#fm_status').combobox({
            data: UserMVC.data.statusList,
            value: 1
        });
    });
}

function ajaxDept() {
    return $.ajax({
        type: UserMVC.Req.findDeptTree.method,
        url: UserMVC.Req.findDeptTree.url,
        dataType: 'json'
    })
        .done(function (data, textStatus, jqXHR) {
            changeTreeGrid2Map(data.data, 'id', 'name', 'children', UserMVC.data.deptMap);
            var treeData = changeTreeGrid2TreeData(data.data, 'id', 'name', 'children');

            $('#deptTree').tree({
                data: treeData,
                loadFilter: e_tree_addall_filter,
                onClick: function (node) {
                    $("#sf_deptId").combotree('setValue', node.id);
                    $('#searchBtn').trigger('click');
                },
                onContextMenu: function (e, node) {
                    e.preventDefault();
                    $(this).tree('select', node.target);
                    $('#mm').menu('show', {
                        left: e.pageX,
                        top: e.pageY
                    });
                }
            });
            $('#sf_deptId').combotree({
                data: treeData,
                loadFilter: e_tree_addall_filter
            });

            $('#fm_deptId').combotree({
                data: treeData
            });
        });
}